package com.wangjw.leetcode;

import java.util.*;

/**
 * Created by wangjw on 18/6/20.
 */
public class LeetCode350 {

    public int[] intersection(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> list = new ArrayList<>();

        for (int num : nums1) {
            if (!map.containsKey(num)) {
                map.put(num, 1);
            } else {
                map.put(num, map.get(num) + 1);
            }
        }

        for (int num : nums2) {
            if (map.containsKey(num)) {
                list.add(num);
                map.put(num, map.get(num) - 1);
                if (map.get(num) == 0) {
                    map.remove(num);
                }
            }
        }

        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }

    public static void main(String[] args) {
        LeetCode350 leetCode804 = new LeetCode350();
        int[] nums1= {1, 2, 2, 1};
        int[] nums2 = {2, 2};

        int[] arr = leetCode804.intersection(nums1, nums2);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
